package com.waimai.www.config;

import java.io.InputStream;
import java.sql.SQLException;

import javax.sql.DataSource;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScan.Filter;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.stereotype.Controller;

import com.alibaba.druid.pool.DruidDataSource;
import com.mysql.cj.jdbc.Driver;
import com.waimai.www.dao.UsersMapper;

@Configuration
@ComponentScan(basePackages = "com.waimai.www", excludeFilters = {
		@Filter(type = FilterType.ANNOTATION, value = Controller.class) })
public class RootConfig {


	@Bean
	public DataSource dataSource() {
		DruidDataSource ds = new DruidDataSource();
		try {
			ds.setDriver(new Driver());
			ds.setUrl("jdbc:mysql://localhost:3306/waimai?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=GMT");
			ds.setUsername("root");
			ds.setPassword("xiaocong2009");
		} catch (SQLException e) {
		}
		return ds;
	}

	@Bean(value="sqlFactory")
	public SqlSessionFactory sessionFactoryBean( DataSource dataSource ) throws Exception {
		
		SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
		bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/*.xml"));
		bean.setDataSource(dataSource);
		return bean.getObject();
	}

	@Bean
	public MapperScannerConfigurer mapperconfig() {
		MapperScannerConfigurer mp = new MapperScannerConfigurer();
		mp.setBasePackage("com.waimai.www.dao");
		mp.setSqlSessionFactoryBeanName("sqlFactory");
		
		return mp; 
	}

}
